<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>编辑文章</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/layuimini/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/layuimini/css/public.css" media="all">
    <link rel="stylesheet" href="/static/admin/layuimini/lib/font-awesome-4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/static/admin/editormd/css/editormd.min.css">
    <link rel="stylesheet" href="/static/admin/my/css/my.css">
</head>
<body>
<div class="layuimini-container" style="background-color: #F2F2F2">
    <div class="layuimini-main">
        <h2><i class="fa fa-edit"></i>&nbsp;文章发布</h2>
        <form class="layui-form layui-form-pane" action="" lay-filter="form-filter" id="article-form">
            <input name="id" type="hidden"/>
            <div class="layui-form-item">
                <label class="layui-form-label">文章标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" lay-verify="verTitle" placeholder="请输入文章标题(必填)..."
                           autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">文章摘要</label>
                <div class="layui-input-block">
                    <input type="text" name="summary" lay-verify="verSummary" placeholder="请输入文章摘要..."
                           autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">封面链接</label>
                <div class="layui-input-block">
                    <input type="text" name="cover" placeholder="请输入封面链接..."
                           autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <div id="test-editor" required lay-verify="verContent">
                    <textarea name="content" style="display:none;"></textarea>
                </div>
            </div>
            <div id="hiddenCy">
                <div class="layui-form-item">
                    <label class="layui-form-label">文章标签</label>
                    <div class="layui-input-block">
                        <div id="tag-select" lay-verify="verTag"></div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">文章类型</label>
                        <div class="layui-input-inline">
                            <select name="type" lay-verify="">
                                <option value="1" selected>原创</option>
                                <option value="2">转载</option>
                                <option value="3">翻译</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">文章分类</label>
                        <div class="layui-input-inline">
                            <select name="categoryId" lay-verify="verCategory" lay-search id="category-select">
                                <option value="0">请选择一个分类</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-form-item">
                            <label class="layui-form-label">开启赞赏</label>
                            <div class="layui-input-inline pane">
                                <input type="checkbox" name="appreciable" lay-skin="switch" lay-text="是|否" checked
                                       value="true">
                            </div>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-form-item">
                            <label class="layui-form-label">开启评论</label>
                            <div class="layui-input-inline pane">
                                <input type="checkbox" name="commentable" lay-skin="switch" lay-text="是|否" checked
                                       value="true">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">是否置顶</label>
                        <div class="layui-input-inline pane">
                            <input type="checkbox" name="top" lay-skin="switch" lay-text="是|否" value="true"
                                   lay-filter="top">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">是否推荐</label>
                        <div class="layui-input-inline pane">
                            <input type="checkbox" name="recommend" lay-skin="switch" lay-text="是|否" value="true"
                                   lay-filter="recommend">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-form-item">
                            <label class="layui-form-label">文章排序</label>
                            <div class="layui-input-inline rate-pane">
                                <div id="rateSort"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div>
                <button type="button" class="layui-btn layui-btn-normal" lay-filter="edit" lay-submit="">更新文章
                </button>
                <button type="button" class="layui-btn layui-btn-warm" lay-filter="draft" lay-submit="">
                    保存草稿
                </button>
                <button type="button" class="layui-btn" lay-filter="publish" lay-submit="">发布文章</button>
            </div>
        </form>
    </div>
</div>

<!-- 注意， 只需要引用 JS，无需引用任何 CSS ！！！-->
<script src="/static/admin/layuimini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/static/admin/layuimini/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/static/admin/xm-select/xm-select.js"></script>
<script src="/static/admin/layuimini/js/lay-module/layuimini/miniTab.js"></script>
<script src="/static/admin/layuimini/lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
<script src="/static/admin/editormd/editormd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
<script type="text/javascript" th:inline="javascript">
    layui.use(['layer', 'form', 'miniTab', 'rate'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            form = layui.form,
            miniTab = layui.miniTab,
            rate = layui.rate;

        //获取分类列表
        $.ajax({
            url: '/admin/category',
            type: 'GET',
            success: function (result) {
                if (result.code == 200) {
                    var cid;
                    if (article != null) {
                        cid = article.categoryId;
                    }
                    $.each(result.data, function () {
                        var categoryId = $(this)[0].id;
                        var categoryName = $(this)[0].name;
                        var categoryOption = $('<option></option>').val(categoryId).text(categoryName);
                        if (cid != null && cid == categoryId) {
                            categoryOption.prop('selected', true);
                        }
                        $('#category-select').append(categoryOption);
                    });
                    form.render('select', 'form-filter');
                }
            }
        });
        //获取标签列表
        $.ajax({
            url: '/admin/tag',
            type: 'GET',
            success: function (result) {
                if (result.code == 200) {
                    var tags = [];
                    $.each(result.data, function () {
                        var tag = {};
                        tag.value = $(this)[0].id;
                        tag.name = $(this)[0].name;
                        tags.push(tag);
                    });
                    if (article != null) {
                        var tagListStr = [], tagList = [[${tagList}]];
                        $.each(tagList, function () {
                            var tag = {};
                            tag.name = $(this)[0].name;
                            tag.value = $(this)[0].id;
                            tagListStr.push(tag);
                        });
                        tagSelect.update({
                            data: tags
                        });
                        tagSelect.setValue(tagListStr);
                    }
                }
            }
        });

        //渲染文章内容
        var article = [[${article}]];
        $('#article-form input[name="id"]').val(article.id);
        $('#article-form input[name="summary"]').val(article.summary);
        $('#article-form input[name="cover"]').val(article.cover);
        $('#article-form input[name="title"]').val(article.title);
        $('#article-form textarea[name="summary"]').val(article.summary);
        $('#article-form textarea[name="content"]').val(article.textContent);
        $('#article-form select[name="type"]').val([article.type]);
        $('#article-form input[name="appreciable"]').prop('checked', article.appreciable);
        $('#article-form input[name="commentable"]').prop('checked', article.commentable);
        $('#article-form input[name="top"]').prop('checked', article.top);
        $('#article-form input[name="recommend"]').prop('checked', article.recommend);
        $('#article-form select[name="categoryId"]').val([article.categoryId]);
        //渲染评分
        var rateSort = rate.render({
            elem: '#rateSort',
            theme: '#009688',
            value: article.sort,
        });
        //渲染多选下拉框
        var tagSelect = xmSelect.render({
            el: '#tag-select',
            language: 'zn',
            //自动换行
            autoRow: true,
            //开启搜索
            filterable: true,
            max: 5,
            theme: {
                maxColor: 'orange',
            },
            create: function (val, arr) {
                if (arr.length === 0) {
                    return {
                        name: val,
                        value: val
                    }
                }
            },
            maxMethod() {
                layer.msg('标签数量不能超过5个');
            },
            data: []
        });
        //渲染编辑器
        var editor = editormd("test-editor", {
            placeholder: '本编辑器支持Markdown编辑，左边编写，右边预览',  //默认显示的文字，这里就不解释了
            width: "100%",
            height: "500px",
            saveHTMLToTextarea: true,
            path: "/static/admin/editormd/lib/"
        });
        form.render();

        //表单验证
        form.verify({
            verTitle: function (value) {
                if (value.length <= 0) {
                    return '文章标题不能为空';
                }
                if (value.length > 100) {
                    return '文章标题长度不能超过100';
                }
            },
            verSummary: function (value) {
                if (value.length > 100) {
                    return '文章摘要长度不能超过100';
                }
            },
            verContent: function () {
                var content = editor.getMarkdown()
                if (content.length <= 0) {
                    return '文章内容不能为空';
                }
            },
            verCategory: function (value) {
                if (value == 0) {
                    return '请选择一个分类';
                }
            },
            verTag: function () {
                if (tagSelect.getValue('value').length <= 0) {
                    return '请选择至少一个标签';
                }
            }
        });
        //监听置顶
        /*   form.on('switch(top)', function (data) {
               if (data.elem.checked) {
                   axios({
                       method: 'get',
                       url: '/admin/article/reachedMaxTop',
                   }).then((response) => {
                       let result = response.data;
                       if (result.data.reached) {
                           data.elem.checked = false;
                           form.render('checkbox');
                           Swal.fire({
                               toast: true,
                               position: 'top-end',
                               icon: 'warning',
                               title: '置顶文章已达到最大限制数量',
                               showConfirmButton: false,
                               timer: 3000,
                               timerProgressBar: true,
                           });
                       }
                   })
                   /!*  $.ajax({
                         url: '/admin/article/reachedMaxTop',
                         type: 'GET',
                         success: function (result) {
                             if (result.data.reached) {
                                 data.elem.checked = false;
                                 form.render('checkbox');
                                 Swal.fire({
                                     toast: true,
                                     position: 'top-end',
                                     icon: 'warning',
                                     title: '置顶文章已达到最大限制数量',
                                     showConfirmButton: false,
                                     timer: 3000,
                                     timerProgressBar: true,
                                 });
                             }
                         }
                     });*!/
               }
           });*/
        //监听推荐
        /* form.on('switch(recommend)', function (data) {
             if (data.elem.checked) {
                 axios({
                     method: 'get',
                     url: '/admin/article/reachedMaxRecommend',
                 }).then((response) => {
                     let result = response.data;
                     if (result.data.reached) {
                         data.elem.checked = false;
                         form.render('checkbox');
                         Swal.fire({
                             toast: true,
                             position: 'top-end',
                             icon: 'warning',
                             title: '推荐文章已达到最大限制数量',
                             showConfirmButton: false,
                             timer: 3000,
                             timerProgressBar: true,
                         });
                     }
                 })
                 /!*  $.ajax({
                       url: '/admin/article/reachedMaxTop',
                       type: 'GET',
                       success: function (result) {
                           if (result.data.reached) {
                               data.elem.checked = false;
                               form.render('checkbox');
                               Swal.fire({
                                   toast: true,
                                   position: 'top-end',
                                   icon: 'warning',
                                   title: '置顶文章已达到最大限制数量',
                                   showConfirmButton: false,
                                   timer: 3000,
                                   timerProgressBar: true,
                               });
                           }
                       }
                   });*!/
             }
         });*/

        //获取输入
        function getField(data) {
            //获取标签列表
            data.field.tagList = tagSelect.getValue().map(item => {
                if (item.value === item.name) {
                    item.value = null;
                }
                return {
                    id: item.value,
                    name: item.name,
                }
            });
            //获取文章内容
            data.field.content = editor.getHTML();
            //获取文章markdown
            data.field.textContent = editor.getMarkdown();
            //获取文章排序
            data.field.sort = rateSort.config.value;
            return data.field;
        };
        //监听保存草稿按钮
        form.on('submit(draft)', function (data) {
            let fields = getField(data);
            //获取是否发布
            fields.published = false;
            axios({
                method: 'put',
                url: '/admin/article',
                data: fields,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
            }).then((response) => {
                Swal.fire({
                    icon: 'success',
                    title: '保存成功',
                    showConfirmButton: false,
                    timer: 1500,
                    onClose: () => {
                        miniTab.openNewTabByIframe({
                            href: "/admin/page/article/article-list?rad=" + Math.random(),
                            title: "文章管理",
                        });
                        //miniTab.deleteCurrentByIframe();
                    }
                });
            }).catch((error) => {
                Swal.fire({
                    icon: 'error',
                    title: '保存失败！',
                    text: `${error.response.data.message}`,
                });
            })
            return false;
        });
        //监听发布文章按钮
        form.on('submit(publish)', function (data) {
            let fields = getField(data);
            //获取是否发布
            fields.published = true;
            Swal.fire({
                title: '是否确定发布该文章',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '确定发布！',
                cancelButtonText: '取消发布！',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return new Promise((resolve, reject) => {
                        axios({
                            method: 'put',
                            url: '/admin/article',
                            data: fields,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        }).then(response => {
                            resolve(response.data);
                        }, error => {
                            reject(error);
                        })
                    }).then(res => {
                        Swal.fire({
                            icon: 'success',
                            title: '发布成功',
                            showConfirmButton: false,
                            timer: 1500,
                            onClose: () => {
                                miniTab.openNewTabByIframe({
                                    href: "/admin/page/article/article-list?rad=" + Math.random(),
                                    title: "文章管理",
                                });
                            }
                        });
                    }).catch(error => {
                        Swal.showValidationMessage(`发布失败: ${error.response.data.message}`);
                    })
                }
            });
            return false;
        });
        //监听更新文章按钮
        form.on('submit(edit)', function (data) {
            let fields = getField(data);
            axios({
                method: 'put',
                url: '/admin/article',
                data: fields,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
            }).then((response) => {
                Swal.fire({
                    icon: 'success',
                    title: '更新成功',
                    showConfirmButton: false,
                    timer: 1500,
                });
            }).catch((error) => {
                Swal.fire({
                    icon: 'error',
                    title: '更新失败！',
                    text: `${error.response.data.message}`,
                });
            })
            return false;
        });
    });
</script>
</body>
</html>